
<template>
  <!-- 会计报表/试算平衡表 页面-->
  <div>
    <cus-allcard :showTitle="false">
      <Tabs :value="tabsValue"
            style="padding-top:16px;min-height:400px"
            @on-click="tabsValueChange($event)">
        <Tab-pane label="经费账科目"
                  name="nameOne">
          <div class="topBody">
            <div class="topBodyItem">
              <span class="itemSpan">账簿年度</span>
              <Select v-model="selectFrom.accountbookId"
                      placeholder="请选择账簿年份"
                      @on-change="accountbookIdChange()"
                      class="itemImport">
                <Option v-for="item in selectFrom.selectModelList"
                        :value="item.accountbookId"
                        :key="item.accountbookId">{{ item.year }}</Option>
              </Select>
            </div>
            <div class="topBodyItem">
              <span class="itemSpan">起始日期</span>
              <Date-picker type="date"
                           v-model="selectFrom.startTime"
                           :clearable="false"
                           :options="timeOptions"
                           placeholder="请选择起始日期"
                           @on-change="tiemStartChange()"
                           class="itemImport"></Date-picker>
            </div>
            <div class="topBodyItem">
              <span class="itemSpan">截止日期</span>
              <Date-picker type="date"
                           v-model="selectFrom.endTime"
                           :clearable="false"
                           :options="timeOptions"
                           placeholder="请选择截止日期"
                           @on-change="tiemEndChange()"
                           class="itemImport"></Date-picker>
            </div>
            <div class="topBodyItem">
              <cus-Button type="primary"
                          @onClick="selectClick"
                          class="ml_10"
                          :disabled="!selectFrom.accountbookId>0"
                          v-permission="20">查询</cus-Button>
            </div>
            <div class="topBodyItem">
              <cus-Button type="primary"
                          class="ml_10"
                          v-if="selectFrom.accountbookId"
                          @onClick="balanceExportByDateApi"
                          v-permission="20">导出</cus-Button>
            </div>
            <!-- <div class="topBodyItem">
              <cus-Button type="primary"
                          @onClick="generateTrialBalance"
                          :disabled="!selectFrom.accountbookId>0||selectFrom.isjiezhuan==1"
                          v-permission="20">生成试算平衡</cus-Button>
            </div> -->
          </div>

          <cusTable border
                 :loading="form.loading"
                 :columns="columnsOne"
                 :data="dataOne"
               
                 :size="vuex_config.tableSize">
            <template slot-scope="{ row }"
                      slot="recmoney">
              {{totalPrices(row.recmoney)}}
            </template>
            <template slot-scope="{ row }"
                      slot="paymoney">
              {{totalPrices(row.paymoney)}}
            </template>
          </cusTable>

        </Tab-pane>
        <Tab-pane label="粮秣账科目"
                  name="nameTwo">
          <div class="topBody">
            <div class="topBodyItem">
              <span class="itemSpan">账簿年度</span>
              <Select v-model="selectFrom.accountbookId"
                      placeholder="请选择账簿年份"
                      :clearable="false"
                      @on-change="accountbookIdChange()"
                      class="itemImport">
                <Option v-for="item in selectFrom.selectModelList"
                        :value="item.accountbookId"
                        :key="item.year">{{ item.year }}</Option>
              </Select>
            </div>
            <div class="topBodyItem">
              <span class="itemSpan">起始日期</span>
              <Date-picker type="date"
                           v-model="selectFrom.startTime"
                           :clearable="false"
                           :options="timeOptions"
                           placeholder="请选择起始日期"
                           @on-change="tiemStartChange()"
                           class="itemImport"></Date-picker>
            </div>
            <div class="topBodyItem">
              <span class="itemSpan">截止日期</span>
              <Date-picker type="date"
                           v-model="selectFrom.endTime"
                           :clearable="false"
                           :options="timeOptions"
                           placeholder="请选择截止日期"
                           @on-change="tiemEndChange()"
                           class="itemImport"></Date-picker>
            </div>
            <div class="topBodyItem">
              <cus-Button type="primary"
                          @onClick="selectClick"
                          class="ml_10"
                          :disabled="!selectFrom.accountbookId>0"
                          v-permission="20">查询</cus-Button>
            </div>
            <div class="topBodyItem">
              <cus-Button type="primary"
                          v-if="selectFrom.accountbookId"
                          @onClick="balanceExportByDateApi"
                          class="ml_10"
                          v-permission="20">导出</cus-Button>
            </div>
            <!-- <div class="topBodyItem">
              <cus-Button type="primary"
                          @onClick="generateTrialBalance"
                          :disabled="!selectFrom.accountbookId>0||selectFrom.isjiezhuan==1"
                          v-permission="20">生成试算平衡</cus-Button>
            </div> -->
          </div>
          <cusTable border
                 :loading="form.loading"
                 :columns="columnsTwo"
                 :data="dataTwo"
             
                 :size="vuex_config.tableSize">
            <template slot-scope="{ row }"
                      slot="recrice">
              {{totalPrices(row.recrice)}}
            </template>

            <template slot-scope="{ row }"
                      slot="recflour">
              {{totalPrices(row.recflour)}}
            </template>

            <template slot-scope="{ row }"
                      slot="recoil">
              {{totalPrices(row.recoil)}}
            </template>

            <template slot-scope="{ row }"
                      slot="recbean">
              {{totalPrices(row.recbean)}}
            </template>
            <template slot-scope="{ row }"
                      slot="payrice">
              {{totalPrices(row.payrice)}}
            </template>

            <template slot-scope="{ row }"
                      slot="payflour">
              {{totalPrices(row.payflour)}}
            </template>

            <template slot-scope="{ row }"
                      slot="payoil">
              {{totalPrices(row.payoil)}}
            </template>

            <template slot-scope="{ row }"
                      slot="paybean">
              {{totalPrices(row.paybean)}}
            </template>
          </cusTable>

        </Tab-pane>
      </Tabs>

    </cus-allcard>
  </div>
</template>
<script>
import {
  getAccountBookByUserId,
  getBalanceReportByDate,
  produceBalanceReport,
  balanceExportByDate
} from '@/api/businessAccountingApi/essentialInformationApi'
export default {
  data () {
    return {
      tabsValue: 'nameOne', // nameOne经费账 nameTwo粮秣账
      subjecttype: 0, // 0经费账 1粮秣账
      form: {
        loading: false,
        name: '',
        startTime: '',
        endTime: ''
      },
      selectFrom: {
        year: null, // 账簿年度
        selectModelList: [], // 账簿年度列表
        tiemList: null, // 查询时间
        startTime: null, // 开始时间-月初
        endTime: null, // 结束时间-月末
        accountbookId: null, // 账簿ID
        department: null // 部门
      },
      dataOne: [], // 经费账-表格列表
      // 经费账-表头
      columnsOne: [
        {
          title: '收方',
          slot: 'recmoney',
          align: 'right',
          minWidth: 100
        },
        {
          title: '科目名称',
          key: 'subjectfullname',
          align: 'center',
          minWidth: 100
        },
        {
          title: '付方',
          slot: 'paymoney',
          align: 'right',
          minWidth: 100
        }
      ],
      retJF: 0, //经费账是否平衡
      retLM: 0, //粮秣账是否平衡

      dataTwo: [], // 粮秣账-表格列表
      // 粮秣账-表头
      columnsTwo: [
        {
          title: '收方(大米)',
          slot: 'recrice',
          align: 'right',
          minWidth: 110
        },
        {
          title: '收方(小麦粉)',
          slot: 'recflour',
          align: 'right',
          minWidth: 120
        },
        {
          title: '收方(食油/千克)',
          slot: 'recoil',
          align: 'right',
          minWidth: 140
        },
        {
          title: '收方(大豆/千克)',
          slot: 'recbean',
          align: 'right',
          minWidth: 140
        },
        {
          title: '科目名称',
          key: 'subjectfullname',
          align: 'center',
          minWidth: 120
        },
        {
          title: '付方(大米)',
          slot: 'payrice',
          align: 'right',
          minWidth: 110
        },
        {
          title: '付方(小麦粉)',
          slot: 'payflour',
          align: 'right',
          minWidth: 120
        },
        {
          title: '付方(食油/千克)',
          slot: 'payoil',
          align: 'right',
          minWidth: 140
        },
        {
          title: '付方(大豆/千克)',
          slot: 'paybean',
          align: 'right',
          minWidth: 140
        }
      ],
      timeOptions: {
        disabledDate (date) {
          return (
            date < new Date(new Date().Format('yyyy') - 1 + '-12-31') || date > new Date(new Date().Format('yyyy-MM-dd'))
          )
        }
      },
      isjiezhuan: null, //是否结转下年
    

    }
  },
  mounted () {
  
 
    // 函数时提示变成3秒消失
    this.$Message.config({
      top: 50,
      duration: 3
    })
    this.getAccountBookByUserIdApi() // 根据用户id查询账簿 接口

  },

  methods: {
    // 千位分割符
    totalPrices (recmoney) {
      const intPart = Math.trunc(recmoney)//整数部分
      let floatPart = 0
      const intPartFormat = intPart.toString().replace(/\B(?=(\d{3})+$)/g, ',')
      const valuArray = Number(recmoney).toString().split('.')

      if (valuArray.length === 2) {//有小数部分
        if (valuArray[1]) {
          if (valuArray[1].length === 1) {
            valuArray[1] += '0'
          }
        } else {
          valuArray[1] = '00'
        }
        floatPart = valuArray[1]//取得小数部分

        return intPartFormat + '.' + floatPart
      } else {
        return intPartFormat + '.00'
      }
    },

    // 根据用户id查询账簿 接口
    getAccountBookByUserIdApi () {
      this.form.loading = true
      console.log(2222222222222222);
      return new Promise((resolve) => {
        getAccountBookByUserId({
          userid: this.vuex_user.base.id// 用户id
        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            this.selectFrom.selectModelList = res.basAccountbookList
            this.selectFrom.accountbookId = res.basAccountbookList[0].accountbookId
            this.selectFrom.department = res.basAccountbookList[0].department
            this.selectFrom.isjiezhuan = res.basAccountbookList[0].isjiezhuan
            if (this.selectFrom.isjiezhuan == 1) {
              this.$Message.info('该账薄已结转')
            }
            this.selectFrom.year = res.basAccountbookList[0].year // 账簿年度
            if (this.selectFrom.year == new Date().Format('yyyy')) { //账簿年度为当前年度
              if (new Date().Format('MM') == '01') { //当是一月份时，时间为 01-01 ~ 01-当前天
                this.selectFrom.startTime = this.selectFrom.year + '-01-01' // 起始日期
                this.selectFrom.endTime = this.selectFrom.year + '-01-' + new Date().Format('dd') // 结束日期
              } else { //当不是一月份时，时间为 01-01 ~ 上个月月尾
                this.selectFrom.tiemList = new Date().Format('yyyy-MM-dd')
                // let yearTime = new Date(this.selectFrom.tiemList).Format('yyyy')
                // let monthTime = new Date(this.selectFrom.tiemList).Format('MM') - 1 //上个月
                // let enddataTime = new Date(yearTime, monthTime, 0).getDate() // 获取上个月最后一天的日 28或29或30或31....
                this.selectFrom.startTime = this.selectFrom.year + '-01-01' // 起始日期
                // this.selectFrom.endTime = yearTime + '-' + monthTime + '-' + enddataTime // 月末
                this.selectFrom.endTime = new Date().Format('yyyy-MM-dd');
                console.log(this.selectFrom,'进入时间');
                
              }
            } else {//账簿年度非当前年度
              this.selectFrom.startTime = this.selectFrom.year + '-01-01' // 起始日期
              this.selectFrom.endTime = this.selectFrom.year + '-12-31' // 结束日期
            }
            console.log(this.selectFrom,'时间');
            
            this.optionDate() // 限制日期封装方法
            this.getBalanceReportByDateApi() // 根据账户ID查询试算平衡表 接口
            resolve()
          } else {
            // this.$Message.error(res.resultMsg)
          }
        })
      })
    },
    // 根据账户ID查询试算平衡表 接口
    getBalanceReportByDateApi () {

      if (this.selectFrom.startTime == '' || this.selectFrom.endTime == '') {
        this.$Message.info("起始/截止日期不能为空")
        return
      }
      this.form.loading = true

      return new Promise((resolve) => {
        getBalanceReportByDate({
          beginDate: this.selectFrom.startTime,
          endDate: this.selectFrom.endTime,
          accountBookId: this.selectFrom.accountbookId// integer 账簿ID
        }).then((res) => {
          this.form.loading = false
          this.dataOne = []
          this.dataTwo = []
          if (res.retCode === 0) {
            this.retJF = res.retJF //经费账是否平衡
            this.retLM = res.retLM //粮秣账是否平衡
            this.dataOne = res.feeRePort
            this.dataTwo = res.stapleRePort
            if (this.retJF != 0) {
              this.$Message.info("经费账账目不平衡")
            }

            resolve()
          } else {
            this.$Message.error(res.retMsg)
          }
        })
      })
    },
    // 生成试算平衡 接口
    produceBalanceReportApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        produceBalanceReport({
          department: this.selectFrom.department, // 部门,  如一连
          operatorname: this.vuex_user.base.name, // 操作人名称
          userid: this.vuex_user.base.id, // 用户id
          abstractType: this.subjecttype, // 摘要类型   0经费账 1粮秣账
          proBalanceDate: new Date().Format('yyyy-MM'), // 格式为  YYYY-mm  生成试算平衡表的日期   用于和当前月比对,只有当前月才能生成试算平衡表
          accountBookId: this.selectFrom.accountbookId// integer 账簿ID

        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            this.getBalanceReportByDateApi() // 根据账户ID查询试算平衡表 接口
            this.$Message.success(res.resultmsg)
            resolve()
          } else {
            this.$Message.error(res.resultmsg)
          }
        })
      })
    },
    // 试算平衡表导出(新) 接口
    balanceExportByDateApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        balanceExportByDate({
          beginDate: new Date(this.selectFrom.startTime).Format('yyyy-MM-dd'), //开始时间	
          endDate: new Date(this.selectFrom.endTime).Format('yyyy-MM-dd'), //结束时间	
          accountBookId: this.selectFrom.accountbookId	//账簿id
        }).then((res) => {
          this.form.loading = false
          if (res.retCode == 0) {
            this.downloads(res.data)
            this.$Message.success(res.retMsg)
            resolve()
          } else {
            this.$Message.error(res.retMsg)
          }
        })
      })
    },
    // tabs标签页改变回调
    tabsValueChange (value) {
      if (value === 'nameOne') { // 经费账科目
        this.subjecttype = 0 // 全局标明为经费账
        if (this.retJF != 0) {
          this.$Message.info("经费账账目不平衡")
        }
      } else { // 粮秣账科目
        this.subjecttype = 1// 全局标明为粮秣
        if (this.retLM != 0) {
          this.$Message.info("粮秣账账目不平衡")
        }
      }
    },
    // 账簿年度改变回调
    accountbookIdChange () {
      this.selectFrom.selectModelList.forEach(element => {
        if (element.accountbookId === this.selectFrom.accountbookId) {
          this.selectFrom.year = element.year
          this.selectFrom.isjiezhuan = element.isjiezhuan
          if (this.selectFrom.isjiezhuan == 1) {
            this.$Message.info('该账薄已结转')
          }
          if (this.selectFrom.year == new Date().Format('yyyy')) { //账簿年度为当前年度

            if (new Date().Format('MM') == '01') { //当是一月份时，时间为 01-01 ~ 01-当前天
              this.selectFrom.startTime = this.selectFrom.year + '-01-01' // 起始日期
              this.selectFrom.endTime = this.selectFrom.year + '-01-' + new Date().Format('dd') // 结束日期
            } else { //当不是一月份时，时间为 01-01 ~ 上个月月尾
              this.selectFrom.tiemList = new Date().Format('yyyy-MM-dd')
              // let yearTime = new Date(this.selectFrom.tiemList).Format('yyyy')
              // let monthTime = new Date(this.selectFrom.tiemList).Format('MM') - 1 //上个月
              // let enddataTime = new Date(yearTime, monthTime, 0).getDate() // 获取上个月最后一天的日 28或29或30或31....
              this.selectFrom.startTime = this.selectFrom.year + '-01-01' // 起始日期
              // this.selectFrom.endTime = yearTime + '-' + monthTime + '-' + enddataTime // 月末
              this.selectFrom.endTime = new Date().Format('yyyy-MM-dd');
            }
          } else {//账簿年度非当前年度
            this.selectFrom.startTime = this.selectFrom.year + '-01-01' // 起始日期
            this.selectFrom.endTime = this.selectFrom.year + '-12-31' // 结束日期
          }
          this.optionDate() // 限制日期封装方法
        }
      })
      this.getBalanceReportByDateApi()
    },
    // 限制日期封装方法
    optionDate () {
      if (this.selectFrom.year == new Date().Format('yyyy')) {
        this.timeOptions = {
          disabledDate (value) {
            return (
              value < new Date(new Date().Format('yyyy') - 1 + '-12-31') || value > new Date(new Date().Format('yyyy-MM-dd'))
            )
          }
        }
      } else {
        let startOption = (Number(this.selectFrom.year) - 1) + '-12-31' // 限制开始能点日期 必须先建变量存储，才能放进new Date()
        let endOption = (Number(this.selectFrom.year)) + '-12-31' // 限制结束能点日期 必须先建变量存储，才能放进new Date()
        this.timeOptions = {
          disabledDate (value) {
            return value < new Date(startOption) || value > new Date(endOption)
          }
        }
      }
    },
    // 起始日期改变回调
    tiemStartChange () {
      this.selectFrom.startTime = new Date(this.selectFrom.startTime).Format('yyyy-MM-dd')
      this.selectFrom.endTime = new Date(this.selectFrom.endTime).Format('yyyy-MM-dd')
      if (new Date(this.selectFrom.startTime).Format('MM') > new Date(this.selectFrom.endTime).Format('MM')) { //起始日期月份 大于 截止日期月份
        this.$Message.info("起始日期大于截止日期")
        this.selectFrom.endTime = ''
      } else if (new Date(this.selectFrom.startTime).Format('MM') == new Date(this.selectFrom.endTime).Format('MM')) { //起始日期月份 等于 截止日期月份
        if (new Date(this.selectFrom.startTime).Format('dd') > new Date(this.selectFrom.endTime).Format('dd')) {
          this.$Message.info("起始日期大于截止日期")
          this.selectFrom.endTime = ''
        }
      }
      console.log('开始时间',this.selectFrom.startTime);
      console.log('结束时间',this.selectFrom.endTime);
    },
    // 截止日期改变回调
    tiemEndChange () {
      this.selectFrom.startTime = new Date(this.selectFrom.startTime).Format('yyyy-MM-dd')
      this.selectFrom.endTime = new Date(this.selectFrom.endTime).Format('yyyy-MM-dd')
      if (new Date(this.selectFrom.startTime).Format('MM') > new Date(this.selectFrom.endTime).Format('MM')) { //起始日期月份 大于 截止日期月份
        this.$Message.success("截止日期大于起始日期")
        this.selectFrom.startTime = ''
      } else if (new Date(this.selectFrom.startTime).Format('MM') == new Date(this.selectFrom.endTime).Format('MM')) { //起始日期月份 等于 截止日期月份
        if (new Date(this.selectFrom.startTime).Format('dd') > new Date(this.selectFrom.endTime).Format('dd')) {
          this.$Message.success("截止日期大于起始日期")
          this.selectFrom.startTime = ''
        }
      }
      console.log('开始时间',this.selectFrom.startTime);
      console.log('结束时间',this.selectFrom.endTime);
    },
    // 查询按钮
    selectClick () {
      // if (this.selectFrom.year == new Date().Format('yyyy')) { //账簿年度为当前年度
      //         if (new Date().Format('MM') == '01') { //当是一月份时，时间为 01-01 ~ 01-当前天
      //           this.selectFrom.startTime = this.selectFrom.year + '-01-01' // 起始日期
      //           this.selectFrom.endTime = this.selectFrom.year + '-01-' + new Date().Format('dd') // 结束日期
      //         } else { //当不是一月份时，时间为 01-01 ~ 上个月月尾
      //           this.selectFrom.tiemList = new Date().Format('yyyy-MM-dd')
      //           // let yearTime = new Date(this.selectFrom.tiemList).Format('yyyy')
      //           // let monthTime = new Date(this.selectFrom.tiemList).Format('MM') - 1 //上个月
      //           // let enddataTime = new Date(yearTime, monthTime, 0).getDate() // 获取上个月最后一天的日 28或29或30或31....
      //           this.selectFrom.startTime = this.selectFrom.year + '-01-01' // 起始日期
      //           // this.selectFrom.endTime = yearTime + '-' + monthTime + '-' + enddataTime // 月末
      //           this.selectFrom.endTime = new Date().Format('yyyy-MM-dd');
      //           console.log(this.selectFrom,'进入时间');
                
      //         }
      //       } else {//账簿年度非当前年度
      //         this.selectFrom.startTime = this.selectFrom.year + '-01-01' // 起始日期
      //         this.selectFrom.endTime = this.selectFrom.year + '-12-31' // 结束日期
      //       }
      this.getBalanceReportByDateApi() // 根据账户ID查询试算平衡表 接口
    },
    // 生成试算平衡按钮
    generateTrialBalance () {
      if (new Date(this.selectFrom.tiemList).Format('yyyy-MM') != new Date().Format('yyyy-MM')) {
        this.$Message.info("只能生成本月试算平衡表")
        return
      }
      this.produceBalanceReportApi() // 生成试算平衡 接口
    },
    // 下载excel
    downloads (url) {
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      function iframeLoad () {
        const win = iframe.contentWindow;
        const doc = win.document;
        if (win.location.href === url) {
          if (doc.body.childNodes.length > 0) {
          }
          iframe.parentNode.removeChild(iframe);
        }
      }
      iframe.src = '';
      document.body.appendChild(iframe)
      setTimeout(function loadUrl () {
        iframe.contentWindow.location.href = url;
      }, 50);
    }
  }
}
</script>
<style lang="less" scoped>
.topBody {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
  flex-wrap: wrap;
  .topBodyItem {
    display: flex;
    align-items: center;
    margin-right: 12px;
    margin-bottom: 20px;
    .itemSpan {
      white-space: nowrap;
      width: 80px;
      text-align: right;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85) !important;
      margin-right: 10px;
    }
    .itemImport {
      width: 200px;
    }
  }
}
</style>
